﻿using Identity.Data.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;

namespace Identity101.Data
{
    public static class Seeder
    {
        public static void Seed(IdentityDbContext db)
        {   
            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
            UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

            RoleStore<Role> roleStore = new RoleStore<Role>(db);
            RoleManager<Role> roleManager = new RoleManager<Role>(roleStore);

            if(!roleManager.RoleExists("General")){
                var result = roleManager.Create(new Role{Name = "General"});
                if (!result.Succeeded) {
                    string errorString = string.Empty;
                    result.Errors.ToList().ForEach(e => errorString += " | " + e);
                }
            }

            if(!roleManager.RoleExists("Admin")){
                roleManager.Create(new Role{ Name = "Admin"});
            }
            //
            ApplicationUser joe = userManager.FindByName("julio@codercamps.com");
            if (joe == null) {
                joe = new ApplicationUser
                {
                    Email = "julio@codercamps.com",
                    UserName = "julio@codercamps.com",
                    Firstname = "Joe",
                    LastName = "Smith"
                };
                userManager.Create(joe, "Joe123!");
                userManager.AddToRole(joe.Id, "Admin");
                joe = userManager.FindByName("julio@codercamps.com");
            } else {
                 // Already exists...
            }

            if (!db.Addresses.Any()) { 
            db.Addresses.AddOrUpdate(a => a.City,
                new Address { City="Pearland", State="TX", Street="123 Elm", Zip="55555", UserId = joe.Id },
                new Address { City="Houston", State="TX", Street="567 York", Zip="77555", UserId = joe.Id }
                );
            }
            db.SaveChanges();


        }


    }
}
